const form = layui.form
//=============================== 获取列表数据 =============================
let params = {
    advimgdesc: '', //广告图片描述
    advimgpos: '', // 广告位
    page: 1, // 页码
    limit: 5// 页数
}
async function rander(params) {
    const paramsdata = await axios.get('/ydd_advimg/list', { params })
    const { data, count } = paramsdata.data.data
    randerPage(count, params)
    randerTable(data)
}
rander(params)

//================================ 渲染表格 =============================
function randerTable(data) {
    layui.use('table', function () {
        const table = layui.table;
        //第一个实例
        table.render({
            elem: '#demo'
            , data: data
            , toolbar: '#toolbarDemo1'
            , defaultToolbar: ``
            // ,width: 1600
            , cols: [[ //表头
                { type: 'checkbox', fixed: 'left', width: 80 }
                , { title: '#', width: 80 }
                , { field: 'advimgpos', title: '广告图位', toolbar: '#toolbarDemo4', }
                , { field: 'advimgdesc', title: '广告图描述', }
                , { field: 'image', title: '广告图', toolbar: '#toolbarDemo3' }
                , { field: 'advimgsrc', title: '广告图链接', }
                , { title: '操作', toolbar: '#toolbarDemo2' }
            ]]
            , done: async function (res) {
                qsa('tbody [data-field="1"] .layui-table-cell').forEach(function (ele, i) {
                    ele.innerHTML = i + 1
                })
                qsa('tbody [name="layTableCheckbox"]').forEach(function (ele, i) {
                    ele['data-id'] = ele.id
                })

            }
        });
        //============================= 头部工具 ==============================
        table.on('toolbar(test)', function (obj) {
            let id = obj.config.id;
            let checkStatus = table.checkStatus(id);
            if (obj.event === 'formChange') {
                const display = qs('form').style.display
                qs('form').style.display = display === 'none' ? 'flex' : 'none'
                const rotate = qs('#formChange i').style.transform
                qs('#formChange i').style.transform = rotate === 'rotate(180deg)' ? 'rotate(0)' : 'rotate(180deg)'
            }
            if (obj.event === 'refresh') {
                location.reload()
            }
            if (obj.event === 'addItem') {
                openList('addItem')
            }
            if (obj.event === 'removeItem') {
                let data = checkStatus.data;
                data.forEach(async ele => {
                    await axios.get(`/ydd_advimg/del`, { params: { id: ele.id } })
                    rander(params)
                })
            }
        })
    });
}
function openList(btnType) {
    layer.open({
        type: 1,
        area: '850px',
        resize: false,
        shadeClose: true,
        title: btnType === 'addItem' ? '添加广告图' : '修改广告图',
        content:
            `<form class="layui-form" lay-filter="filter" id="addOrEdit">
                <div class="layui-form-item">
                    <label class="layui-form-label" lay-verify><i>*</i>广告位</label>
                    <select name="advimgpos">
                        <option value="">请选择</option>
                    </select>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label" lay-verify><i>*</i>广告图描述</label>
                    <div class="layui-input-block">
                        <input type="text" name="advimgdesc" placeholder="请输入广告图描述" autocomplete="off" class="layui-input">
                    </div>
                </div>  
                <div class="layui-form-item">
                    <label class="layui-form-label" lay-verify><i>*</i>广告图链接</label>
                    <div class="layui-input-block">
                        <input type="text" name="advimgsrc" placeholder="请输入广告图链接" autocomplete="off" class="layui-input">
                    </div>
                </div>                
                <div class="layui-form-item last">
                    <label class="layui-form-label" lay-verify><i>*</i>广告图</label>
                    <div class="layui-input-block">
                        <input type="file" name="advimglink" placeholder="请选择上传图片" autocomplete="off" style="display:none">
                        <div class="showPic">
                            <img src="" alt="" class="pic">
                            <p class="openLp">点击查看图片详情</p>
                            <label><i class="fa fa-check"></i></label>
                            <i class="fa fa-close close"></i>
                        </div>
                        <button type="button" class="layui-btn layui-btn-normal" id="upload">上传图片</button>
                    </div>
                </div>                
            </form>`,
        btn: ['提交', '重置'],
        btn1: async function (index) {
            const form = layui.form
            if (!qs('[name="advimgpos"]').value) return layer.msg('请输入广告位', { time: 1000 })
            if (!qs('[name="advimgdesc"]').value) return layer.msg('请输入广告图描述', { time: 1000 })
            if (!qs('[name="advimglink"]').files[0]) return layer.msg('请选择图片', { time: 1000 })
            await axios.post(
                btnType === 'addItem' ? `/ydd_advimg/add` : `/ydd_advimg/update`
                , 'addItem' ? form.val('filter') : {
                    advimgdesc: qs('[name="advimgdesc"]').value,
                    advimglink: qs('[name="advimglink"]').value,
                    advimgpos: qs('[name="advimgpos"]').value,
                    advimgsrc: qs('[name="advimgsrc"]').value,
                    id: btnType
                }
            )
            rander(params)
            layer.close(index)
        },
        btn2: function () {
            const form = layui.form
            form.val('filter', {
                advimgpos: '',
                advimgsrc: '',
                advimglink: '',
                advimgdesc: ''
            })
            return false
        },
        anim: 5,
        success: async function () {
            const form = layui.form
            //渲染下拉菜单
            const paramsdata = await axios.get('/ydd_advimg/all')
            const data = paramsdata.data.data
            let arr = []
            data.forEach(ele => {
                arr.includes(ele.advimgpos) ? '' : arr.push(ele.advimgpos)
            })
            qs('[name="advimgpos"]').innerHTML += arr.sort((a, b) => a - b).map(ele => `<option value="${ele}">${ele}</option>`).join('')
            form.render('select', 'filter')
            ///编辑相关功能
            if (btnType !== 'addItem') {
                const info = await axios.get('/ydd_advimg/rowInfo', { params: { id: btnType } })
                const data = info.data.data
                ////表单赋值
                qs('[name="advimgdesc"]').value = data.advimgdesc
                qs('[name="advimgsrc"]').value = data.advimgsrc
                ///下拉框选中
                const pos = qsa('[name="advimgpos"] option')
                for (let i = 0; i < pos.length; i++) {
                    if (pos[i].value === data.advimgpos) {
                        pos[i].selected = true
                        form.render()
                    }
                }
            }
            ///显示大图
            qs('.openLp').addEventListener('click', async function () {
                layer.open({
                    type: 1,
                    area: '770px',
                    resize: false,
                    shadeClose: true,
                    title: '图片',
                    content: `<img src="" alt="" class="pic-l">`,
                    success: function () {
                        qs('.pic-l').src = qs('.pic').src
                    }
                })
            })
            ///
            qs('[name="advimglink"]').addEventListener('change', async function () {
                const upInfo = qs('[name="advimglink"]')
                if (!upInfo.files[0]) return;

                //处理样式
                qs('#upload').style.display = 'none'
                qs('.showPic').style.display = 'flex'
                qs('.last').style.height = '125px'


                ///处理数据发送请求
                let aa = new FormData()
                aa.append('file', upInfo.files[0])
                //发送现有信息
                let data = await axios.post(`/common/upload?type=images`, aa)
                qs('.pic').src = `http://124.223.14.236:8060/${data.data.data.savePath}`
                //自行渲染图片链接
                qs('[name="advimgsrc"]').value = data.data.data.savePath
            })

        }
    })
}



//============================ 筛选功能 =============================
qs('#search').addEventListener('submit', async function (e) {
    e.preventDefault()
    params.advimgname = qs('[name="name"]').value.trim()
    rander(params)
})
//============================= 渲染分页器 =============================
function randerPage(count, params) {
    layui.use('laypage', function () {
        const laypage = layui.laypage
        laypage.render({
            elem: 'laypage' //注意，这里的 test1 是 ID，不用加 # 号
            , count: count //数据总数，从服务端得到
            , limit: params.limit
            , curr: params.page
            , limits: [2, 3, 5, 10]
            , layout: ['count', 'limit', 'prev', 'page', 'next', 'skip']
            , theme: '#1E9FFF'
            , prev: `<i class="fa fa-angle-left left-nav-li"></i>`
            , next: `<i class="fa fa-angle-right left-nav-li"></i>`
            , jump: function (obj, first) {
                if (!first) {
                    params.page = obj.curr
                    params.limit = obj.limit
                    rander(params)
                }
            }
        });
    })
}
//================================== 行删除/编辑 =============================
qs('body').addEventListener('click', function (e) {
    const target = e.target
    /* 删除 */
    if (target.className.includes('delItem')) {
        const layer = layui.layer;
        layer.confirm('确认删除？', {
            btn: ['确认', '取消']
            , btn1: async function (index) {
                await axios.get(`/ydd_advimg/del`, { params: { id: target.dataset.id } })
                rander(params)
                layer.close(index)
            }
        });
    }
    /* 编辑 */
    if (target.className.includes('editItem')) {
        openList(target.dataset.id)
    }
    ///点击按钮收集图片
    if (target.id === 'upload') {
        qs('[name="advimglink"]').click()
    }
    if (target.className.includes('close')) {
        qs('.showPic').style.display = 'none'
        qs('#upload').style.display = 'inline-block'
        qs('[name="advimglink"]').value = ''
        qs('.last').style.height = '38px'
    }
})
//============================ 筛选功能 =============================
qs('#search').addEventListener('submit', async function (e) {
    e.preventDefault()
    params.advimgdesc = qs('[name="advimgdesc"]').value.trim()
    params.advimgpos = qs('[name="advimgpos"]').value.trim()
    rander(params)
})